<template>
  <div>
    <!-- 查询表单 -->
    <el-form :inline="true" :model="searchForm" class="mb-2">
      <el-form-item label="商品名称">
        <el-input v-model="searchForm.cmdtyTitle" placeholder="请输入商品名称" />
      </el-form-item>
      <el-form-item label="标签">
        <el-input v-model="searchForm.cmdtyTag" placeholder="请输入标签" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchList">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 新增按钮 -->
    <el-button type="primary" @click="openDialog()" class="mb-2">新增商品</el-button>

    <!-- 商品表格 -->
    <el-table :data="tableData" class="mb-2">
      <el-table-column prop="cmdtyId" label="ID" width="60" />
      <el-table-column prop="cmdtyTitle" label="商品名称" />
      <el-table-column prop="cmdtyBrief" label="简介" />
      <el-table-column prop="cmdtyCost" label="单价" />
      <el-table-column prop="cmdtyTag" label="标签" />
      <el-table-column prop="cmdtyAddedAt" label="上架时间" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteProduct(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination v-model:current-page="searchForm.page" v-model:page-size="searchForm.pageSize"
      :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" background />

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="商品名称" prop="cmdtyTitle">
          <el-input v-model="form.cmdtyTitle" />
        </el-form-item>
        <el-form-item label="简介" prop="cmdtyBrief">
          <el-input v-model="form.cmdtyBrief" type="textarea" />
        </el-form-item>
        <el-form-item label="单价" prop="cmdtyCost">
          <el-input-number v-model="form.cmdtyCost" :min="0" :step="0.01" />
        </el-form-item>
        <el-form-item label="标签" prop="cmdtyTag">
          <el-input v-model="form.cmdtyTag" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { addCommodityApi, AdgetCommodityApi, deleteCommodityApi, updateCommodityApi } from '@/api/commodity'
import type { Commodity } from '@/types/commodity'
import { useAdminStore } from '@/store/admin'

const searchForm = reactive({
  cmdtyTitle: '',
  cmdtyTag: '',
  page: 1,
  pageSize: 10
})
const useAdmin = useAdminStore()
const tableData = ref<Commodity[]>([])
const total = ref<number>(0)
const dialogVisible = ref<boolean>(false)
const dialogTitle = ref<string>('新增商品')
const form = reactive<Partial<Commodity>>({
  cmdtyId: undefined,
  cmdtyTitle: '',
  cmdtyBrief: '',
  cmdtyCost: 0,
  cmdtyTag: '',
  cmdtyMgrId: undefined,
  cmdtyAddedAt: ''
})
const rules: FormRules = {
  cmdtyTitle: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  cmdtyCost: [{ required: true, message: '请输入单价', trigger: 'blur' }]
}
const formRef = ref<FormInstance | null>(null)

async function fetchList() {
  const res = await AdgetCommodityApi(searchForm);
  if (res.code == 200) {
    ElMessage.success(res.msg)
    tableData.value = res.data.list
  } else {
    ElMessage.error(res.msg)
  }
}
function resetSearch(): void {
  searchForm.cmdtyTitle = ''
  searchForm.cmdtyTag = ''
  searchForm.page = 1
  fetchList()
}
function openDialog(row?: Commodity): void {
  if (row) {
    dialogTitle.value = '编辑商品'
    Object.assign(form, row)
  } else {
    dialogTitle.value = '新增商品'
    Object.assign(form, { cmdtyId: undefined, cmdtyTitle: '', cmdtyBrief: '', cmdtyCost: 0, cmdtyTag: '', cmdtyMgrId: undefined, cmdtyAddedAt: '' })
  }
  dialogVisible.value = true
}
async function submitForm(): Promise<void> {
  if (form.cmdtyId) {
    // 编辑逻辑
    console.log(form)
    const res = await updateCommodityApi(form as Commodity)
    if (res.code == 200) {
      ElMessage.success(res.msg)
      dialogVisible.value = false
      fetchList()
    }
  } else {
    // 添加逻辑
    if (useAdmin.admin) {
      form.cmdtyMgrId = useAdmin.admin.adminId
    }
    const res = await addCommodityApi(form as Commodity)
    if (res.code == 200) {
      ElMessage.success(res.msg)
      dialogVisible.value = false
      fetchList()
    }
  }
}
async function deleteProduct(row: Commodity): Promise<void> {
  try {
    await ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    const res = await deleteCommodityApi(row)
    if (res.code == 200) {
      ElMessage.success(res.msg)
      fetchList()
    } else {
      ElMessage.error(res.msg)
      fetchList()
    }
  } catch (e) {
    // 用户取消，无需处理
  }
}
function handleSizeChange(size: number): void {
  searchForm.pageSize = size
  searchForm.page = 1
  fetchList()
}
function handleCurrentChange(page: number): void {
  searchForm.page = page
  fetchList()
}
// 页面加载时获取数据
onMounted(() => {
  fetchList();


});
</script>

<style scoped>
.mb-2 {
  margin-bottom: 16px;
}
</style>
